//
//  LoginViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-10-21.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "CitesViewController.h"
#import "RegisterHelper.h"
#import "CustomerModel.h"
#import "CustomGuidView.h"
#import "ForgotPwdViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
{
    NSMutableArray *data;
}
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self initLoginView];
    [self.passwordField setSecureTextEntry:YES];
    self.phoneNumTextField.delegate = self;
    self.passwordField.delegate = self;
    self.passwordField.returnKeyType = UIReturnKeyGo;
    self.phoneNumTextField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"usersPhoneNum"];
    self.passwordField.text =[[NSUserDefaults standardUserDefaults]objectForKey:@"usersPassword"];
    
}


- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardWasShow:)
                                                name:UIKeyboardDidShowNotification
                                              object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardWillBeHidden:)
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
}

- (void)unregisterForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardDidShowNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardWillHideNotification
                                                 object:nil];
}

-(void)initLoginView{
    
    data = [[NSMutableArray alloc]initWithCapacity:1];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    CGRect frame = CGRectMake((kWidth - 153)/2,64, 153,133);
    if(!IS_4_INCH_SCREEN){
        frame = CGRectMake((kWidth - 133)/2,44, 133, 113);
    }
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
    imageView.image = [UIImage imageNamed:@"logo_register"];
    [self.view addSubview:imageView];
    

}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    [self.phoneNumTextField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    [UIView animateWithDuration:0.3f animations:^{

            self.view.transform = CGAffineTransformMakeTranslation(0, 0);
        
    }];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.passwordField.delegate = self;
    self.phoneNumTextField.delegate  = self;
    [self.navigationController.navigationBar setHidden:YES];
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self unregisterForKeyboardNotifications];
    self.passwordField.delegate = nil;
    self.phoneNumTextField.delegate  = nil;
    [self.navigationController.navigationBar setHidden:NO];

}

- (void)dealloc{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)loginIn:(UIButton *)sender {
    
    
    BOOL isValid = [DataUtility isPhoneNumberValid:self.phoneNumTextField.text];
    
    if (isValid && self.passwordField.text != nil && ![self.passwordField.text isEqualToString:@""]) {
       
        
        [self loginMethodWithParams];
        
    }else{
        if (!isValid) {
            
            [UIUtility showAlertViewWithTitle:@"提示" messsge:@"电话号码格式有误!"];
        
        }else{
            
            [UIUtility showAlertViewWithTitle:@"提示" messsge:@"请输入正确密码!"];
            
        }
        
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"usersPhoneNum"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"usersPassword"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [self.passwordField resignFirstResponder];
    [self.phoneNumTextField resignFirstResponder];
    [UIView animateWithDuration:0.3f animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
    
}

//调登录接口
- (void)loginMethodWithParams{
    
    [self showProgressHUDWithTitle:@"登录中..."];
    NSString *password = [self.passwordField.text md5];
    NSString *vcode = BUNDLE_VERSION;
    NSInteger c = vcode.integerValue;
    vcode = [NSString stringWithFormat:@"%ld",(long)c];
    NSNumber *pm = @1;
    NSString *appCode = @"1001";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    SetValueForKey(params, self.phoneNumTextField.text, @"tel");
    SetValueForKey(params,password, @"psd");
    SetValueForKey(params, vcode, @"vcode");
    SetValueForKey(params, pm, @"pm");
    SetValueForKey(params, appCode, @"appCode");
    
    
    __weak LoginViewController *weak_self = self;
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kLogin
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         [weak_self hideProgressHUD];
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             NSString *msg = [responseDic objectForKey:@"msg"];
                             NSLog(@"%@",msg);
                             DLog(@"获取参数  %@",responseDic);
                             
                             BOOL result= [[responseDic objectForKey:@"result"]boolValue];
                             
                             if (!result) {
                                 
                                 NSArray *list = [responseDic objectForKey:@"prodcutType"];
                                 
                                 [RegisterHelper shareHelper].score = [responseDic objectForKey:@"score"];
                                 [RegisterHelper shareHelper].userId = [responseDic objectForKey:@"userId"];
                                 [RegisterHelper shareHelper].citesName = [responseDic objectForKey:@"comnityName"];
                                 [RegisterHelper shareHelper].citesId = [responseDic objectForKey:@"comnityId"];
                                 [RegisterHelper shareHelper].registerPhoneNum = self.phoneNumTextField.text;
                                 
                                 for (NSDictionary *dic in list) {
                                     CustomerModel *customerModel = [[CustomerModel alloc]initWithCustomerInfo:dic];
                                     [data addObject:customerModel];
                                 }
                                 [RegisterHelper shareHelper].productArray = data;
                                 [weak_self gotoAppDelgate:responseDic];
                                 [[NSUserDefaults standardUserDefaults] setObject:self.phoneNumTextField.text forKey:@"usersPhoneNum"];
                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                
                                 [[NSUserDefaults standardUserDefaults] setObject:self.passwordField.text forKey:@"usersPassword"];
                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                 
                             }else{
                                 
                                 DLog(@"登录失败 %@",responseDic);
                                 
                                 [self showToastMessage:[responseDic objectForKey:@"msg"]];
                                 
                             }
                         }
                         else{
                             
                             [self showToastMessage:response.errorMessage];
                         }
                            }];
}

-(void)gotoAppDelgate:(NSDictionary *)userModel{
    
    [[AppDelegate sharedDelegate] initCustomerModel:userModel];
//    [self dismissViewControllerAnimated:YES completion:nil];
     [APP_DELEGATE initMainViewControllerWithStoryBoardIdentifier:@"MainViewController" type:0 pushIn:self];

}



-(IBAction)visitorAction:(id)sender{
    
//    VisitorViewController *visitorVC = [[NSBundle mainBundle]loadNibNamed:@"VisitorViewController" owner:self options:nil][0];
//    [self.navigationController pushViewController:visitorVC animated:YES];
    
    CitesViewController *citesVC = [[CitesViewController alloc]init];
    citesVC.hidesBottomBarWhenPushed = YES;
    citesVC.isRegister = NO;
    [self.navigationController pushViewController:citesVC animated:YES];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField.returnKeyType == UIReturnKeyGo) {
        BOOL isValid = [DataUtility isPhoneNumberValid:self.phoneNumTextField.text];
        
        if (isValid && self.passwordField.text != nil && ![self.passwordField.text isEqualToString:@""]) {
            
            
            [self loginMethodWithParams];
            
        }else{
            
            if (!isValid) {
                
                [UIUtility showAlertViewWithTitle:@"提示" messsge:@"电话号码格式有误!"];
                
                
            }else{
                
                [UIUtility showAlertViewWithTitle:@"提示" messsge:@"请输入正确密码!"];
            }
            
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"usersPhoneNum"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"usersPassword"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
    
    [self.passwordField resignFirstResponder];

    return YES;
}

- (void)keyboardWasShow:(NSNotification *)notification {
    // 取得键盘的frame，注意，因为键盘在window的层面弹出来的，所以它的frame坐标也是对应window窗口的。
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGPoint endOrigin = endRect.origin;
    // 把键盘的frame坐标系转换到与UITextView一致的父view上来。
    if ([UIApplication sharedApplication].keyWindow && self.view) {
        endOrigin = [self.view convertPoint:endRect.origin fromView:[UIApplication sharedApplication].keyWindow];
    }
    
    [UIView animateWithDuration:0.3f animations:^{
        if(!IS_4_INCH_SCREEN){
             self.view.transform = CGAffineTransformMakeTranslation(0, -150);
        }else{
            self.view.transform = CGAffineTransformMakeTranslation(0, -100);
        }
    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)notification{

    [UIView animateWithDuration:0.3f animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
@end
